/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UI_Asociaciones.java
 *
 * Created on May 3, 2010, 1:41:30 PM
 */

package UI;


import Excepciones.DinamicaDato;
import Excepciones.ProcesamientoDato;
import Excepciones.Sistema;
import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import Modelo.BaseDato;
import robot_maker.Accesorio;
import robot_maker.Manager;
import robot_maker.ResultSetTableModel;

/**
 *
 * @author CarlosScipione
 */
public class UI_Asociaciones extends javax.swing.JFrame {
    private int codRobot;
    private int rowR;
    private int rowAcc;

    /** Creates new form UI_Asociaciones */
    public UI_Asociaciones() {
        initComponents();
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);
    }

     private void llenar (JTable tabla, String query) {
            try{
            try {
                BaseDato buscar = new BaseDato();
            } catch (CommunicationsException ex) {
                        Sistema.loggear(10, "LLENAR",
                        "COMUNICACION PERDIDA CON LA BASE DE DATOS",
                        UI_Asociaciones.class, "CommunicationsException");
            } catch (DinamicaDato ex) {
            }
            tabla.setModel(new ResultSetTableModel(query));
            if (tabla.getRowCount() > 0) {
                tabla.setRowSelectionInterval(0, 0);
            }
        } catch (ClassNotFoundException ex) {
        Logger.getLogger(UI_Tienda.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
        Logger.getLogger(UI_Tienda.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        robot_table = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        acc_tabla = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        robot_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        robot_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                robot_tableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(robot_table);

        jLabel1.setText("Asociaciones Disponibles:");

        jLabel3.setText("Accesorio:");

        jLabel2.setText("Robots:");

        acc_tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        acc_tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                acc_tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(acc_tabla);

        jButton1.setText("+");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("-");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(464, Short.MAX_VALUE)
                .add(jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(28, 28, 28))
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jLabel1)
                        .add(layout.createSequentialGroup()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel2)
                                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 248, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel3)
                                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 264, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(17, 17, 17)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton1)
                    .add(jButton3))
                .addContainerGap(345, Short.MAX_VALUE))
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .add(28, 28, 28)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(jLabel2)
                            .add(8, 8, 8))
                        .add(jLabel3))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(jScrollPane1, 0, 0, Short.MAX_VALUE)
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 275, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void robot_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_robot_tableMouseClicked
        JTable target = (JTable)evt.getSource();
        int row = target.getSelectedRow();
        rowR =row;
        int column = target.getSelectedColumn();
        ResultSet lista = null;
        try {
            lista = BaseDato.ejecutarSqlSelect("select r.id \"Codigo\", " +
                    "r.nombre \"Nombre\", r.descripcion \"Descripcion\" " +
                    "from ROBOT r");
        } catch (DinamicaDato ex) {
        }
        int i = 0;
        while (i <= row){
            try {
                lista.next();
                i++;
            } catch (SQLException ex) {
        Logger.getLogger(UI_Tienda.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            codRobot = lista.getInt(1);
            llenar(acc_tabla, "select a.id \"Codigo\", a.nombre \"Nombre\", "+
                  "a.caracteristicas \"Descripcion\" from ACCESORIO a, " +
                  "ASOCIACION aa where aa.accesorio_id=a.id and aa.robot_id="
                  + codRobot);
            try {
                lista = BaseDato.ejecutarSqlSelect("select count(a.id) from " +
                        "ACCESORIO a, ASOCIACION aa where aa.accesorio_id=a.id "
                        + "and aa.robot_id=" + codRobot);
            } catch (DinamicaDato ex) {
            }
             lista.next();
             if(lista.getInt(1) == 0)
                 JOptionPane.showMessageDialog(null,
                    "Este robot no posee ningun accesorio asociado.");
        } catch (SQLException ex) {
        Logger.getLogger(UI_Tienda.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_robot_tableMouseClicked

    private void acc_tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acc_tablaMouseClicked

}//GEN-LAST:event_acc_tablaMouseClicked

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
          llenar(robot_table, "select r.id \"Codigo\", r.nombre \"Nombre\", " +
                  "r.descripcion \"Descripcion\" from ROBOT r");
    }//GEN-LAST:event_formWindowOpened

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        AsociacionRA window = new AsociacionRA();
        window = (AsociacionRA) Manager.centra(window);
        window.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        try {
            rowAcc = acc_tabla.getSelectedRow() + 1;
            ResultSet lista = null;
            try {
                lista = BaseDato.ejecutarSqlSelect("select a.id, a.nombre, "+
                  "a.caracteristicas from ACCESORIO a, " +
                  "ASOCIACION aa where aa.accesorio_id=a.id and aa.robot_id="
                  + codRobot);
            } catch (DinamicaDato ex) {
            }
            try {
                int i = 1;
                lista.next();
                while (i < rowAcc) {
                    lista.next();
                    i++;
                }
            } catch (SQLException ex) {
                Sistema.loggear(11, "MouseClicked", "EN EL SQL DE EJECUCCION",
                        UI_Accesorios.class, "SQLException");
            }
            Accesorio des = new Accesorio();
            des.desasociar(codRobot, lista.getInt(1));
        } catch (SQLException ex) {
            Sistema.loggear(11, "MouseClicked", "EN EL SQL DE EJECUCCION",
                        UI_Robots.class, "SQLException");
        } catch (ProcesamientoDato ex) {
        }
  

    }//GEN-LAST:event_jButton3ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UI_Asociaciones().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable acc_tabla;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable robot_table;
    // End of variables declaration//GEN-END:variables

}
